<template>
  <div class="item-management">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h2 class="page-title">物品管理</h2>
      </div>
      <div class="header-right">
        <el-button type="primary" :icon="Plus" size="large" @click="handleAdd">
          添加物品
        </el-button>
      </div>
    </div>

    <!-- 搜索筛选栏 -->
    <el-card class="filter-card" shadow="never">
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="搜索" label-width="50px">
          <el-input 
            v-model="searchForm.keyword" 
            placeholder="搜索物品名称或描述"
            clearable
            size="default"
            style="width: 250px"
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="分类" label-width="50px">
          <el-select 
            v-model="searchForm.category" 
            placeholder="请选择分类"
            clearable
            size="default"
            style="width: 150px"
            @change="handleSearch"
          >
            <el-option label="纸类" value="纸类" />
            <el-option label="塑料" value="塑料" />
            <el-option label="金属" value="金属" />
            <el-option label="玻璃" value="玻璃" />
            <el-option label="纺织品" value="纺织品" />
            <el-option label="有害垃圾" value="有害垃圾" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" size="default" @click="handleSearch">搜索</el-button>
          <el-button :icon="Refresh" size="default" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card" shadow="never">
      <el-table 
        v-loading="loading" 
        :data="tableData" 
        stripe
        style="width: 100%"
        row-key="id"
      >
        <el-table-column prop="name" label="物品名称" width="150" show-overflow-tooltip>
          <template #default="{ row }">
            <span class="table-text">{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="category" label="分类" width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="getCategoryType(row.category)" size="default">{{ row.category }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="unit" label="单位" width="100" align="center">
          <template #default="{ row }">
            <span class="table-text">{{ row.unit }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="pricePerUnit" label="单价（元）" width="130" align="center">
          <template #default="{ row }">
            <span class="price">￥{{ row.pricePerUnit }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" min-width="300" show-overflow-tooltip>
          <template #default="{ row }">
            <span class="table-text">{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.status === 'active' ? 'success' : 'info'" size="default">
              {{ row.status === 'active' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="240" align="center">
          <template #default="{ row }">
            <el-button type="primary" link size="default" :icon="Edit" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button 
              :type="row.status === 'active' ? 'warning' : 'success'" 
              link 
              size="default" 
              @click="handleToggleStatus(row)"
            >
              {{ row.status === 'active' ? '禁用' : '启用' }}
            </el-button>
            <el-button type="danger" link size="default" :icon="Delete" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogTitle"
      width="600px"
      @close="resetForm"
    >
      <el-form 
        ref="formRef" 
        :model="formData" 
        :rules="formRules" 
        label-width="100px"
      >
        <el-form-item label="物品名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入物品名称" />
        </el-form-item>
        <el-form-item label="物品分类" prop="category">
          <el-select v-model="formData.category" placeholder="请选择分类" style="width: 100%">
            <el-option label="纸类" value="纸类" />
            <el-option label="塑料" value="塑料" />
            <el-option label="金属" value="金属" />
            <el-option label="玻璃" value="玻璃" />
            <el-option label="纺织品" value="纺织品" />
            <el-option label="有害垃圾" value="有害垃圾" />
          </el-select>
        </el-form-item>
        <el-form-item label="计量单位" prop="unit">
          <el-select v-model="formData.unit" placeholder="请选择单位" style="width: 100%">
            <el-option label="千克（kg）" value="kg" />
            <el-option label="个" value="个" />
            <el-option label="件" value="件" />
            <el-option label="吨" value="t" />
          </el-select>
        </el-form-item>
        <el-form-item label="单价" prop="pricePerUnit">
          <el-input-number 
            v-model="formData.pricePerUnit" 
            :precision="2"
            :step="0.1"
            :min="0"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="物品描述" prop="description">
          <el-input 
            v-model="formData.description" 
            type="textarea" 
            :rows="3" 
            placeholder="请输入物品描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="handleSubmit">
          {{ editingId ? '更新' : '创建' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh, Edit, Delete } from '@element-plus/icons-vue'
import { itemsAPI } from '@/api'

// 响应式数据
const loading = ref(false)
const submitting = ref(false)
const dialogVisible = ref(false)
const editingId = ref(null)
const tableData = ref([])
const formRef = ref(null)

// 搜索表单
const searchForm = reactive({
  keyword: '',
  category: null
})

// 分页数据
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// 表单数据
const formData = reactive({
  name: '',
  category: null,
  unit: 'kg',
  pricePerUnit: 0,
  description: ''
})

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入物品名称', trigger: 'blur' },
    { min: 2, max: 50, message: '物品名称长度在2-50个字符', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择物品分类', trigger: 'change' }
  ],
  unit: [
    { required: true, message: '请选择计量单位', trigger: 'change' }
  ],
  pricePerUnit: [
    { required: true, message: '请输入单价', trigger: 'blur' },
    { type: 'number', min: 0, message: '单价不能为负数', trigger: 'blur' }
  ]
}

// 计算属性
const dialogTitle = computed(() => editingId.value ? '编辑物品' : '添加物品')

// 方法
const loadData = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      pageSize: pagination.pageSize,
      ...searchForm
    }
    const response = await itemsAPI.getItems(params)
    tableData.value = response.list
    pagination.total = response.total
  } catch (error) {
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.page = 1
  loadData()
}

const resetSearch = () => {
  Object.assign(searchForm, {
    keyword: '',
    category: null
  })
  handleSearch()
}

const getCategoryType = (category) => {
  const types = {
    '纸类': 'success',
    '塑料': 'warning',
    '金属': '',
    '玻璃': 'info',
    '纺织品': 'success',
    '有害垃圾': 'danger'
  }
  return types[category] || 'info'
}

const handleAdd = () => {
  editingId.value = null
  resetForm()
  dialogVisible.value = true
}

const handleEdit = (row) => {
  editingId.value = row.id
  Object.assign(formData, row)
  dialogVisible.value = true
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除物品"${row.name}"吗？`,
      '确认删除',
      {
        type: 'warning'
      }
    )
    
    await itemsAPI.deleteItem(row.id)
    ElMessage.success('删除成功')
    loadData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const handleToggleStatus = async (row) => {
  const newStatus = row.status === 'active' ? 'inactive' : 'active'
  const action = newStatus === 'active' ? '启用' : '禁用'
  
  try {
    await ElMessageBox.confirm(
      `确定要${action}物品"${row.name}"吗？`,
      `确认${action}`,
      {
        type: 'warning'
      }
    )
    
    await itemsAPI.updateItemStatus(row.id, newStatus)
    ElMessage.success(`${action}成功`)
    loadData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(`${action}失败`)
    }
  }
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitting.value = true
    
    if (editingId.value) {
      await itemsAPI.updateItem(editingId.value, formData)
      ElMessage.success('更新成功')
    } else {
      await itemsAPI.createItem(formData)
      ElMessage.success('创建成功')
    }
    
    dialogVisible.value = false
    loadData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(editingId.value ? '更新失败' : '创建失败')
    }
  } finally {
    submitting.value = false
  }
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.page = 1
  loadData()
}

const handleCurrentChange = (page) => {
  pagination.page = page
  loadData()
}

const resetForm = () => {
  Object.assign(formData, {
    name: '',
    category: null,
    unit: 'kg',
    pricePerUnit: 0,
    description: ''
  })
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 生命周期
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.item-management {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.page-title {
  margin: 0;
  font-size: 22px;
  font-weight: 600;
  color: #303133;
}

.filter-card {
  margin-bottom: 12px;
  border-radius: 8px;
}

:deep(.filter-card .el-card__body) {
  padding: 16px 20px;
}

.search-form {
  margin-bottom: 0;
}

:deep(.search-form .el-form-item) {
  margin-bottom: 0;
  margin-right: 16px;
}

:deep(.search-form .el-form-item__label) {
  font-size: 15px;
  color: #606266;
  font-weight: 500;
}

:deep(.search-form .el-input__inner) {
  font-size: 15px;
}

:deep(.search-form .el-button) {
  font-size: 15px;
  padding: 9px 18px;
}

.table-card {
  border-radius: 8px;
}

:deep(.table-card .el-card__body) {
  padding: 0;
}

:deep(.el-table) {
  font-size: 15px;
}

:deep(.el-table th.el-table__cell) {
  background-color: #fafafa;
  color: #606266;
  font-weight: 600;
  font-size: 15px;
  padding: 14px 0;
}

:deep(.el-table td.el-table__cell) {
  padding: 14px 0;
}

.table-text {
  font-size: 15px;
  color: #303133;
}

:deep(.el-table .el-button) {
  font-size: 15px;
  padding: 6px 10px;
  margin: 0 2px;
}

:deep(.el-table .el-tag) {
  font-size: 14px;
  padding: 4px 10px;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
  padding: 16px 20px;
}

:deep(.el-pagination) {
  font-size: 15px;
}

:deep(.el-pagination .el-pager li) {
  font-size: 15px;
  min-width: 32px;
  height: 32px;
  line-height: 32px;
}

.price {
  color: #67c23a;
  font-weight: 600;
  font-size: 15px;
}

.dialog-footer {
  text-align: right;
}
</style>








